/**  
 * 
 * @Title:  MybatisShardingPlugin.java   
 * @Package com.scrapy.process.Interceptor   
 * @Description:    TODO(用一句话描述该文件做什么)   
 * @author: 123774135@qq.com     
 * @date:   2018年7月4日 下午2:12:46   
 * @version V1.0 
 * @Copyright: 2018 www.tydic.com Inc. All rights reserved. 
 * 
 */  
package com.bicon.base.data.common.mybatis.interceptor;

import java.sql.Connection;
import java.util.Properties;

import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bicon.base.data.common.mybatis.annotation.sharding.TableSeg;

/**   
 * @ClassName:  MybatisShardingPlugin   
 * @Description:进行水平切分拦截，根据自定义注解去判断切分规则   
 * @author: 123774135@qq.com 
 * @date:   2018年7月4日 下午2:12:46   
 *     
 * @Copyright: 2018 
 * 
 */
@Intercepts(@Signature(type=StatementHandler.class ,method="prepare",args= {Connection.class,Integer.class}))
public class MybatisShardingPlugin implements Interceptor {

	private Logger logger = LoggerFactory.getLogger(MybatisShardingPlugin.class);
	
	@Override
	public Object intercept(Invocation arg0) throws Throwable {
		logger.info("进入Sharding区域");
		StatementHandler statementhandler = (StatementHandler) arg0.getTarget();
		MetaObject metaobject = SystemMetaObject.forObject(statementhandler);
		//分离h对象
		while(metaobject.hasGetter("h")) {
			Object object = metaobject.getValue("h");
			metaobject = SystemMetaObject.forObject(object);
		}
		//分离target对象
		while(metaobject.hasGetter("target")) {
			Object object = metaobject.getValue("target");
			metaobject = SystemMetaObject.forObject(object);
		}
		MappedStatement mappedStatement = (MappedStatement)metaobject.getValue("delegate.mappedStatement");
		String classandmethod = mappedStatement.getId();
		//获取mapper所在的类
		String strclass = classandmethod.substring(0, classandmethod.lastIndexOf("."));
		System.out.println(strclass);
		Class<?> clazz = Class.forName(strclass);
		TableSeg tableSeg =  clazz.getAnnotation(TableSeg.class);//获取水平切分注解类
	//	BoundSql boundSql = statementhandler.getBoundSql();
		//BoundSql boundSql = statementhandler.getBoundSql();
		return arg0.proceed();
	}

	@Override
	public Object plugin(Object arg0) {
		
		return Plugin.wrap(arg0, this);
	}

	@Override
	public void setProperties(Properties arg0) {
		
	}

}
